import 'dart:convert';
import 'dart:io';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:wanchong/app/app.dart';
import 'package:wanchong/bean/im_entity.dart';
import 'package:wanchong/bean/im_user_info_android_entity.dart';
import 'package:wanchong/bean/im_user_info_entity.dart';
import 'package:wanchong/public.dart';

class ImChat extends StatefulWidget {
  final String nick;
  ImChat({Key key, this.nick});
  @override
  _ImChatState createState() => _ImChatState();
}

class _ImChatState extends State<ImChat> {
  var self = imUserSelf;
  // ImUserInfoEntity other, own;
  String otherFace, ownFace = "";
  int page = 1;
  List<ImEntity> messages = [];
  List<_History> _msgs = [];
  @override
  void initState() {
    ///注册消息接受
    String event = "$ImMessage${widget.nick}";
    print(event);
    eventBus.on(event, (dynamic data) {
      print("收到消息了");
      // _msgs.add();
      _msgs.insert(
          0, _History(self: false, content: data, succ: true, sending: false));
      setState(() {});
    });
    getUser();
    getData(page);
    super.initState();
  }

  final TextEditingController _textController =
      new TextEditingController(); //聊天窗口的文本输入控件
  @override
  void dispose() {
    String event = "$ImMessage${widget.nick}";
    eventBus.off(event);
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        elevation: 0.0,
      ),
      body: Column(
        children: <Widget>[
          Flexible(
            child: ListView.builder(
              reverse: true,
              itemBuilder: (BuildContext context, int index) =>
                  _buildContent(_msgs[index]),
              itemCount: _msgs.length,
            ),
          ),
          Divider(
            height: 1.0,
          ),
          _buildTextComposer()
        ],
      ),
    );
  }

  //定义文本输入框控件
  Widget _buildTextComposer() {
    return new Container(
        margin: const EdgeInsets.symmetric(horizontal: 8.0),
        child: new Row(//文本输入和发送按钮都在同一行，使用Row控件包裹实现
            children: <Widget>[
          new Flexible(
            child: new TextField(
              controller: _textController, //载入文本输入控件
              onSubmitted: _handleSubmitted,
              decoration: new InputDecoration.collapsed(
                  hintText: "Send a message"), //输入框中默认提示文字
            ),
          ),
          new Container(
            margin: new EdgeInsets.symmetric(horizontal: 4.0),
            child: new IconButton(
              //发送按钮
              icon: new Icon(Icons.send), //发送按钮图标
              onPressed: () => _handleSubmitted(_textController.text),
            ), //触发发送消息事件执行的函数_handleSubmitted
          ),
        ]));
  }

  Widget _buildContent(_History item) {
    if (item.self) {
      ///如果是对方的消息，就放在左边
      return Container(
        margin: const EdgeInsets.only(
          top: 10.0,
          bottom: 10.0,
          left: 120,
        ),
        child: Row(
          children: <Widget>[
            Expanded(
              child: Container(
                margin: EdgeInsets.only(right: 10.0),
                alignment: Alignment.topRight,
                child: Text(item.content),
              ),
            ),
            Container(
              width: 40,
              height: 40,
              child: ClipOval(
                child: ClipOval(
                  child: ownFace != ""
                      ? CachedNetworkImage(
                          imageUrl: ownFace,
                          fit: BoxFit.cover,
                        )
                      : Image.asset(
                          "assets/default.png",
                          fit: BoxFit.cover,
                        ),
                ),
              ),
            ),
          ],
        ),
      );
    } else {
      ///如果是自己的消息，就放在右边
      return Container(
        margin: const EdgeInsets.only(top: 5.0, right: 120.0),
        child: Row(
          children: <Widget>[
            Container(
              width: 40,
              height: 40,
              child: ClipOval(
                child: otherFace != ""
                    ? CachedNetworkImage(
                        imageUrl: otherFace,
                        fit: BoxFit.cover,
                      )
                    : Image.asset(
                        "assets/default.png",
                        fit: BoxFit.cover,
                      ),
              ),
            ),
            Expanded(
              child: Container(
                alignment: Alignment.topLeft,
                child: Text(item.content),
              ),
            ),
          ],
        ),
      );
    }
  }

  //定义发送文本事件的处理函数
  void _handleSubmitted(String text) async {
    _textController.clear(); //清空输入框
    try {
      // _msgs.add();
      _msgs.insert(
          0, _History(self: true, content: text, succ: false, sending: true));
      setState(() {});
      var res = await dim.sendTextMessages(widget.nick, text);
      if (res == "send message ok") {
        ///消息发送成功
      } else {
        ///消息发送失败
      }
      // print("SendMessag？e = $res");
      _msgs[_msgs.length].sending = false;
      _msgs[_msgs.length].succ = true;
      setState(() {});
      print("send message res=$res");
    } catch (err) {
      print(err);
    }
  }

  getData(int page) async {
    try {
      int count = page * 20;
      String c = await dim.getMessages(widget.nick, count);
      print(c);
      List msgs = json.decode(c);
      // List<ImEntity> messageList = msgs.map((m)=>ImEntity.fromJson(m)).toList();
      // messages.clear();
      // messages.addAll(msgs.map((m) => ImEntity.fromJson(m)).toList());
      for (int i = 0; i < msgs.length; i++) {
        // print(i);

        ImEntity item = ImEntity.fromJson(msgs[i]);
        // print("widget.nick=${widget.nick},timConversation.peer=${item.sender}");
        _msgs.add(new _History(
            self: widget.nick != item.sender,
            content: item.message.text,
            succ: true,
            sending: false));
      }
      print(_msgs.length);
      setState(() {});
    } catch (err) {
      print("getUser");
      print(err);
    }
  }

  getUser() async {
    print("get UserInfo");
    var res = await dim.getUsersProfile([widget.nick, self.nick]);
    print(res);
    List infos = json.decode(res);
    if (Platform.isIOS) {
      var _own = ImUserInfoEntity.fromJson(infos[1]);
      // print(own.faceUrl);
      var _other = ImUserInfoEntity.fromJson(infos[0]);

      ownFace = _own.faceUrl;
      otherFace = _other.faceUrl;
      print("ios$ownFace");
    } else {
      var _own = ImUserInfoAndroidEntity.fromJson(infos[1]);
      // print(own.faceUrl);
      var _other = ImUserInfoAndroidEntity.fromJson(infos[0]);
      ownFace = _own.faceUrl;
      otherFace = _other.faceUrl;
    }

    setState(() {});
  }
}

class _History {
  bool self;
  // String face;
  bool succ;
  String content;
  bool sending;
  _History({this.self, this.content, this.succ = false, this.sending = true});
}
